<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $loginFieldName = config('admin.login.username');

        $rules = [
            $loginFieldName => 'required',
            'password'      => 'required|string|between:6,20',
        ];

        $params = $request->validate($rules);

        return ($token = auth('api')->attempt($params))
            ? response()->json([
                'status' => true,
                'msg'    => '登录成功',
                'token'  => "bearer {$token}",
            ])
            : response([
                'errors' => [
                    $loginFieldName => '账号或密码不对',
                ],
            ], 422);
    }

    public function logout()
    {
        auth('api')->logout();

        return response()->json([
            'status' => true,
            'msg'    => '已退出',
        ]);
    }

    public function info()
    {
        return response()->json(auth('api')->user());
    }
}
